﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media.Media3D;
using System.Windows.Media;
using System.Windows;
using System.Diagnostics;

namespace Zero.UControl.Component.Notification
{
    public class NotificationHost : Window
    {
        private StackPanel _panel;

        public NotificationHost()
        {
            Width = 320;
            Height = SystemParameters.WorkArea.Height;
            Top = SystemParameters.WorkArea.Top;
            Left = SystemParameters.WorkArea.Right - Width;
            WindowStyle = WindowStyle.None;
            AllowsTransparency = true;
            Background = Brushes.Transparent;
            ShowInTaskbar = false;
            Topmost = true;

            _panel = new StackPanel
            {
                VerticalAlignment = VerticalAlignment.Bottom,
                Margin = new Thickness(0, 0, 10, 10)
            };
            
            Content = _panel;

            // 监听主窗口关闭事件（易发生内存泄露,下面是改进的方式）
            // if (Application.Current.MainWindow != null)
            // {
            //     Application.Current.MainWindow.Closed += (s, e) => this.Close();
            // }
            /*
                如果你使用 mainWindow.Closed += ...，主窗口引用会被持有，可能导致 MainWindow 或 NotificationHost 无法被 GC。
                WeakEventManager 内部是弱引用机制，不会阻止 GC 回收监听者或事件源，推荐在需要长时间监听但不能泄漏内存的场景中使用。
            */
            // 使用 WeakEventManager 防止内存泄漏
            var mainWindow = Application.Current.MainWindow;
            if (mainWindow != null)
            {
                WeakEventManager<Window, EventArgs>.AddHandler(mainWindow, nameof(mainWindow.Closed), OnMainWindowClosed);
            }
        }

        private void OnMainWindowClosed(object? sender, EventArgs e)
        {
            this.Close();
        }

        public void ShowNotification(string title, string message, int durationSeconds = 3)
        {
            ShowNotification(title, message,null, durationSeconds);
        }


        public void ShowNotification(string title, string message,FrameworkElement element, int durationSeconds = 3)
        {
            if (!IsVisible)
                this.Show();
            var toast = new ToastNotification();
            toast.Closed += Toast_Closed;
            toast.Show(title, message,element, durationSeconds);
            _panel.Children.Add(toast);
        }

        private void Toast_Closed(object? sender, EventArgs e)
        {
            if (sender is ToastNotification notification)
            {
                _panel.Children.Remove(notification);
                if (_panel.Children.Count == 0)
                {
                    this.Hide();
                }
            }
        }
    }

}
